import random
import string
import uuid

import jwt
from django.core.cache import cache
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken

from apps.app01 import models
from apps.app01.extensions import jwtt
from lenovo import settings


class LoginCode(APIView):
    """验证码登录"""

    authentication_classes = []

    def post(self, request):
        email = request.data.get('email')
        code = request.data.get('code')
        letters = string.ascii_lowercase
        if email:
            cache_code = cache.get(email)
            if not cache_code:
                return JsonResponse({'code': 400, 'message': '验证码已失效，请重新获取'}, status=400)
            if str(cache_code) != str(code):
                return JsonResponse({'code': 401, 'message': '验证码错误，请重新输入'}, status=401)
            cache.delete(email)
            user = models.User.objects.filter(email=email).first()
        if not user:
            user = models.User(nickname=str(uuid.uuid4()).replace('-', ''),
                                password=''.join(random.choice(letters) for i in range(8)), email=email)
            user.save()
        payload = jwtt.jwt_payload_handler(user)
        access_token = jwt.encode(payload=payload, key=settings.SECRET_KEY, algorithm='HS256')
        refresh_token = RefreshToken.for_user(user)
        return JsonResponse({'code': 200, 'message': 'OK',
                             'data': {'access_token': access_token, 'refresh_token': str(refresh_token)}},
                            status=200)